package com.study.webapp.socket.netty.http.xml.codec;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.util.CharsetUtil;

import java.util.List;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class HttpXmlRequestDecoder extends AbstractHttpXmlDecoder<FullHttpRequest> {

    public HttpXmlRequestDecoder(Class<?> clazz) {
       this(clazz,false);
    }

    public HttpXmlRequestDecoder(Class<?> clazz, boolean isPrint) {
        super(clazz, isPrint);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, FullHttpRequest request, List<Object> list) throws Exception {
        if (!request.getDecoderResult().isSuccess()) {
            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                    BAD_REQUEST, Unpooled.copiedBuffer("Failure: " + BAD_REQUEST.toString()
                    + "\r\n", CharsetUtil.UTF_8));
            response.headers().set(CONTENT_TYPE,"text/plain; charset=UTF-8");
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
            return;
        }
        HttpXmlRequest request1 = new HttpXmlRequest(request,decoder0(ctx,request.content()));
        list.add(request1);
    }
}
